using System;
using System.Timers;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using API;
using Grpc.Core;
using mb;
using Mb;
using Xamarin.Forms;

class TestObject
{
	public static int ObjCount = 0;
	static int ObjId = 0;
	private Timer tm;
	private int id = 0;
	private int sec = 0;

	public TestObject()
	{
		id = ObjId++;
		ObjCount++;
	}

	~TestObject()
	{
		ObjCount--;
		Console.WriteLine("~TestObject:{0}", id);
		tm?.Stop();
	}

	void onTimer(object sender, ElapsedEventArgs eventArgs)
	{
		var mid = id;
		// var msec = sec;
		Console.WriteLine("** timer id:{1}, objcount:{0}", ObjCount, id);
		// Console.WriteLine("** timer id:{1}, sec:{2}, objcount:{0}", ObjCount, mid, msec);
		if (++sec >= 5)
		{
			tm.Stop();
			// tm.Elapsed -= onTimer;
			Console.WriteLine("** stop: {0}", mid);
			// new Thread(() =>
			// {
			// 	int i = 5;
			// 	while (--i > 0)
			// 	{
			// 		Thread.Sleep(3000);
			// 		Console.WriteLine("** wait: {0}, {1}", mid, i);
			// 	}
			//
			// 	Console.WriteLine("** recover: {0}", mid);
			// 	// sec = 0;
			// 	// tm.Start();
			// }).Start();
		}
	}

	public void Start()
	{
		tm = new Timer(1000);
		tm.Elapsed += onTimer;
		// tm.Elapsed += delegate (object sender, ElapsedEventArgs args) { onTimer(sender, args); };
		tm.Start();
	}

	public void Stop()
	{
		Console.WriteLine("stop:{0}", id);
		tm.Stop();
	}
}

namespace libhot
{
	public class TestGcPage : ContentPage
	{
		public TestGcPage()
		{
			// this.EnableNavBar(false);

			var hrm = CatLib.App.Make<HotReloadManager>();
			hrm.RegisterReloadWeak(this, "testgc", (self, resName) =>
			{
				var me = self as TestGcPage;
				me.Content = null;
				me.LoadXamlFromRes(resName);
				this.DoLoad();
			});
		}

		public string TimerCount { get; set; }
		Timer tmTest;
		protected async void DoLoad()
		{
			tmTest = new Timer();
			int i = 0;
			tmTest.Elapsed += delegate
			{
				TimerCount = $"timer:{i++}";
				OnPropertyChanged(nameof(TimerCount));
			};
			// tmTest.Start();
		}


		void DoGC(object sender, EventArgs arg)
		{
			GC.Collect();
			GC.WaitForPendingFinalizers();
			App.logger.Log("-- gc: {0}", TestObject.ObjCount);
		}

		void AddTestObject(object sender, EventArgs arg)
		{
			new TestObject().Start();
		}


	}
}